<template>
  <div class="header">
    <el-button @click="addManagerInfoBtn" type="primary">
      添加管理员 <el-icon class="el-icon--right"><Plus /></el-icon>
    </el-button>
  </div>
  <el-table
    :header-cell-style="headerCellStyle"
    :cell-style="{ textAlign: 'center' }"
    :data="computedTableData"
    style="width: 100%"
  >
    <el-table-column type="index" label="序号" width="80" />
    <el-table-column prop="adminname" label="账户" />
    <el-table-column label="权限">
      <template #default="scope">
        <el-tag effect="dark" :type="scope.row.role === 1 ? '' : 'success'">{{
          scope.row.role === 1 ? '管理员' : '超级管理员'
        }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)">Edit</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)"
          >Delete</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <!--渲染分页-->
  <el-pagination
    background
    layout="prev,pager,next,total"
    :total="tableData.length"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
  />

  <!--右侧的抽屉-->
  <el-drawer
    v-model="showDrawer"
    :title="currentType === 1 ? '添加管理员' : '修改管理员'"
  >
    <el-form
      label-position="right"
      label-width="100px"
      :model="formData"
      style="max-width: 460px"
    >
      <el-form-item label="账户">
        <el-input v-model="formData.adminname" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="formData.password" :disabled="currentType === 2" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="formData.role" class="m-2" size="large">
          <el-option label="管理员" value="1"></el-option>
          <el-option label="超级管理员" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限">
        <el-tree
          ref="treeRef"
          :data="menus"
          show-checkbox
          node-key="path"
          default-expand-all
          :default-checked-keys="defaultCheckedKeys"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="showDrawer = false">cancel</el-button>
        <el-button
          v-if="currentType === 1"
          type="primary"
          @click="addManagerBtn"
          >添加</el-button
        >
        <el-button v-else type="primary" @click="updateManagerBtn"
          >修改</el-button
        >
      </div>
    </template>
  </el-drawer>
</template>

<script>
import {
  getManagerList,
  deleteManager,
  addManager,
  updateManager
} from '@/api/user'
import { Plus } from '@element-plus/icons-vue'
import { routes } from '@/router'
import { mapState, mapMutations } from 'vuex'
import _ from 'lodash'
export default {
  components: {
    Plus
  },
  methods: {
    ...mapMutations(['updateUserInfo']),
    // 最上面的点击添加管理员按钮
    addManagerInfoBtn() {
      this.formData.adminname = ''
      this.formData.password = ''
      this.formData.role = '1'
      this.formData.checkedKeys = []
      this.defaultCheckedKeys = []
      if (this.$refs.treeRef) {
        this.$refs.treeRef.setCheckedKeys([])
      }
      this.currentType = 1
      this.showDrawer = true
    },
    updateCheckedKeys() {
      let list = this.$refs.treeRef.getCheckedNodes(true) // [{管理员列表},{管理员列表2}]
      const tempList = []
      const result = []
      list.forEach((item) => {
        const parent = this.menus.find((mitem) => {
          return mitem.children.some((child) => child.label === item.label)
        })
        // console.log('---parent-', parent)
        if (!tempList.includes(parent.label)) {
          tempList.push(parent.label) // ['账户管理']
          result.push({
            // result=[{label:'账户管理',path:'manerg',children:[{管理员列表}]}]
            label: parent.label,
            path: parent.path,
            children: [item]
          })
        } else {
          // console.log('---result', result)
          result.find((item) => item.label === parent.label).children.push(item)
        }
      })
      this.formData.checkedKeys = result
    },
    // 点击drawer底部的修改管理员按钮
    updateManagerBtn() {
      this.updateCheckedKeys()
      updateManager(this.formData).then(() => {
        // 如果点击的是当前用户的权限，立即修改
        if (this.userInfo.adminname === this.formData.adminname) {
          // 需要将vuex的userInfo的checkedkys更改
          this.userInfo.checkedkeys = this.formData.checkedKeys
          this.updateUserInfo(this.userInfo)
        }
        this.showDrawer = false
        this.getTableList()
      })
    },
    // 点击drawer底部的添加管理员按钮
    addManagerBtn() {
      this.updateCheckedKeys()
      this.addManagerInfo()
    },
    addManagerInfo() {
      addManager(this.formData).then(() => {
        this.showDrawer = false
        this.getTableList()
      })
    },
    // 点击table里面的编辑，进行管理员信息的回填操作
    handleEdit(row) {
      this.currentType = 2
      this.showDrawer = true
      this.formData.adminname = row.adminname
      this.formData.password = row.password
      this.formData.role = row.role.toString()
      this.formData.checkedKeys = row.checkedKeys

      // tree回显的时候的默认defaultCheckedKeys的设置，里面放字符串的path
      const checkedKeys = []
      row.checkedKeys.forEach((parent) => {
        parent.children.forEach((child) => {
          checkedKeys.push(child.path)
        })
      })
      this.defaultCheckedKeys = checkedKeys

      // 希望tree里面可以进行选中，只是更改了formData的checkedKeys是不行的
      if (this.$refs.treeRef) {
        this.$refs.treeRef.setCheckedKeys(checkedKeys)
      }
    },
    handleDelete(row) {
      deleteManager({
        adminid: row.adminid
      }).then(() => {
        this.getTableList() // 重新请求管理员列表数据
        this.currentPage = 1 // 页码回到第一页
      })
    },
    getTableList() {
      getManagerList().then((res) => {
        this.tableData = res.data || []
      })
    }
  },
  data() {
    return {
      currentType: 1,
      menus: routes[0].children,
      defaultCheckedKeys: [], //默认选中的数组
      formData: {
        adminname: '',
        password: '',
        role: '1',
        checkedKeys: []
      },
      showDrawer: false, // 打开右侧添加管理员的抽屉面板
      currentPage: 1,
      pageSize: 10,
      headerCellStyle: {
        color: 'rgba(0,0,0,0.85)',
        fontWeight: '700',
        fontSize: '14px',
        textAlign: 'center',
        background: '#f8f8f8',
        height: '60px',
        borderRight: '1px solid #f0f0f0',
        transition: 'background .3s ease'
      },
      tableData: []
    }
  },
  created() {
    // 剔除bannerAdd这个导航
    // console.log('this.menus----->', this.menus[1].children.pop())

    const cloneRoutes = _.cloneDeep(routes[0].children) // 每次需要clone一份新的
    cloneRoutes[1].children.pop()
    this.menus = cloneRoutes
    this.getTableList()
  },
  computed: {
    ...mapState(['userInfo']),
    computedTableData() {
      return this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        (this.currentPage - 1) * this.pageSize + this.pageSize
      )
    }
  }
}
</script>

<style scoped lang="scss">
.header {
  margin-bottom: 24px;
}
</style>
